import React from 'react'
import { ImagePicker } from 'antd-mobile';
import axios from 'axios'

// const data = [{
//   url: 'https://zos.alipayobjects.com/rmsportal/PZUUCKTRIHWiZSY.jpeg',
//   id: '2121',
// }, {
//   url: 'https://zos.alipayobjects.com/rmsportal/hqQWgTXdrlmVVYi.jpeg',
//   id: '2122',
// }];
const data = []

class ImagePickerExample extends React.Component {
  state = {
    files: data,
    images: []
  }

  static getDerivedStateFromProps(props, state) {
    if (props.images !== state.images && Array.isArray(props.images)) {
      return {
        files: props.images.map((e, i) => ({
          id: new Date().getTime + i,
          url: e
        }))
      }
    }
    return null
  }

  onChange1 = async (files, type, index) => {
    console.log(files, 'onchamge');
    if (!files || !files.length) {
      return
    }

    var form = new FormData();
    form.append("file", files[0].file);
    form.append("bucket", "dxtoss");
    console.log(form, 'form');
    try {
      const res = await axios({
        data: form,
        url: "/wmjapi/upload",
        method: "post"
      })
      this.state.images.push({
        url: res.data.url,
        id: new Date().getTime()
      })
      this.props.imageChange(this.state.images)
    } catch (err) {
      throw err
    }
  }

  onChange = (files, type, index) => {
    console.log(files, type, index);
    switch (type) {
      case 'remove':
        files.splice(index, 1)
        break;
      case 'add':
        
      default:
        break;
    }
    // this.onChange1(files)
    console.log(files, 'files');
    this.setState({
      files,
    });
  }

  render() {
    const { files } = this.state;
    const { multiple, selectable = false } = this.props
    console.log(!multiple && files.length === 0, '!multiple && files.length === 0');
    return (
      <ImagePicker
        files={files}
        onChange={this.onChange}
        onImageClick={(index, fs) => console.log(index, fs)}
        selectable={files.length < 7}
        multiple={multiple}
        selectable={selectable}
      />
    );
  }
}

export default ImagePickerExample